import requests
from loguru import logger

from basic.assert_template import AssertTemplate
from config import ENV
from const import merchant_path

class BaseAPI:
    _MER_HOST = ""
    _PLAT_HOST = ""
    _USER_HOST = ""

    def send_mer_requests(self, api_name, data: dict):
        if self._MER_HOST:
            data.update({"url": self._MER_HOST + data["url"]})
        logger.info(f"{api_name}__的请求信息为：{data}")
        response = requests.request(**data)
        logger.info(f"{api_name}__的响应信息为：{response.text}")
        return response.json()

    def send_plat_requests(self, api_name, data: dict):
        if self._PLAT_HOST:
            data.update({"url": self._PLAT_HOST + data["url"]})
        logger.info(f"{api_name}__的请求信息为：{data}")
        response = requests.request(**data)
        logger.info(f"{api_name}__的响应信息为：{response.text}")
        return response.json()

    def send_user_requests(self, api_name, data: dict):
        if self._USER_HOST:
            data.update({"url": self._USER_HOST + data["url"]})
        logger.info(f"{api_name}__的请求信息为：{data}")
        response = requests.request(**data)
        logger.info(f"{api_name}__的响应信息为：{response.text}")
        return response.json()

class Login(BaseAPI):
    def __init__(self):
        self._MER_HOST = ENV.MER_HOST
        self._PLAT_HOST = ENV.PLAT_HOST
        self._USER_HOST = ENV.USER_HOST

        self.mer_token = self.__mer_login()
        self.plat_token = self.__plat_login()
        self.user_token = self.__user_login()

        self.assert_temp = AssertTemplate()
        self.mer_json_path = str(merchant_path)

    def __mer_login(self):
        data = {
            "method": "post",
            "url": "/api/admin/merchant/login",
            "headers": {"content-type": "application/json"},
            "json": {"account": "18292417675", "pwd": "000000", "captchaVO": {},
                     "captcha": {"captchaVerification": "", "secretKey": "", "token": ""}}
        }
        return self.send_mer_requests(self.__mer_login.__name__, data)["data"]["token"]

    def __plat_login(self):
        data = {
            "method": "post",
            "url": "/api/admin/platform/login",
            "headers": {"content-type": "application/json"},
            "json": {"account": "demo", "pwd": "crmeb.com", "captchaVO": {}}
        }
        return self.send_plat_requests(self.__plat_login.__name__, data)["data"]["token"]

    def __user_login(self):
        data = {
            "method": "post",
            "url": "/api/front/login/mobile/password",
            "headers": {"content-type": "application/json"},
            "json": {"phone": "17362124646", "password": "a123456", "spreadPid": 0}
        }
        return self.send_user_requests(self.__user_login.__name__, data)["data"]["token"]

if __name__ == '__main__':
    Login()
